package cn.exrick.manager.service.impl;

import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.manager.mapper.TbArticleMapper;
import cn.exrick.manager.pojo.TbArticle;
import cn.exrick.manager.pojo.TbArticleExample;
import cn.exrick.manager.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private TbArticleMapper tbArticleMapper;

    @Override
    public void addArticle(TbArticle tbArticle) {
        tbArticle.setCreateTime(new Date());
        tbArticle.setUpdateTime(new Date());
        tbArticleMapper.insert(tbArticle);
    }

    @Override
    public void deleteArticle(List<Long> ids) {
        TbArticleExample example = new TbArticleExample();
        TbArticleExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        tbArticleMapper.deleteByExample(example);
    }

    @Override
    public void updateArticle(TbArticle tbArticle) {
        tbArticle.setUpdateTime(new Date());
        tbArticleMapper.updateByPrimaryKeySelective(tbArticle);
    }

    @Override
    public TbArticle getArticle(Long id) {
        return tbArticleMapper.getArticleById(id);
    }

    @Override
    public DataTablesResult getArticleList(int draw, int start, int length, TbArticle tbArticle, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();
        //分页
        PageHelper.startPage(start/length+1,length);
        List<TbArticle> tbArticles = tbArticleMapper.selectByCondition(tbArticle,orderCol,orderDir);
        PageInfo<TbArticle> pageInfo = new PageInfo<>(tbArticles);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal((int)pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(tbArticles);
        return result;
    }


    @Override
    public TbArticle getArticleByNavId(Long id) {
        TbArticleExample example = new TbArticleExample();
        TbArticleExample.Criteria criteria = example.createCriteria();
        criteria.andNavIdEqualTo(id);
        List<TbArticle> tbArticles = tbArticleMapper.selectByExampleWithBLOBs(example);
        if(CollectionUtils.isEmpty(tbArticles)){
            return null;
        }
        return tbArticles.get(0);
    }
}
